package com.ray.system.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.builder.CompanyBuilder;
import com.ray.system.builder.CompanyInfoBuilder;
import com.ray.system.check.CompanyCheck;
import com.ray.system.service.SysCompanyInfoService;
import com.ray.system.service.SysCompanyService;
import com.ray.system.service.compose.CompanyService;
import com.ray.system.service.compose.UserService;
import com.ray.system.table.dto.CompanyInfoDTO;
import com.ray.system.table.dto.CompanyQueryDTO;
import com.ray.system.table.entity.SysCompany;
import com.ray.system.table.params.company.*;
import com.ray.system.table.vo.company.CompanyVO;
import com.ray.template.TemplateFactory;
import com.ray.template.TemplateRecord;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 公司相关服务
 * @Class: CompanyApi
 * @Package com.ray.system.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class CompanyApi {

    @Autowired
    private SysCompanyService sysCompanyService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SysCompanyInfoService sysCompanyInfoService;
    @Autowired
    private UserService userService;


    /**
     * 查询公司列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<CompanyVO>> pageCompanys(CommonPage<CompanyQueryParams, Page<CompanyVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<CompanyQueryDTO, SysCompany> commonPageBuilder = new CommonPageBuilder<>(CompanyQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendParentCompanyCode(loginUser.getCompanyCode())
                .appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<SysCompany> page = sysCompanyService.page(commonPageBuilder.bulid(), loginUser);
        List<SysCompany> Companys = page.getRecords();
        //结果对象
        IPage<CompanyVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(Companys)) {
            pageList.setRecords(Companys.stream().map(sysCompany -> {
                CompanyVO CompanyVO = new CompanyVO();
                BeanUtil.copyProperties(sysCompany, CompanyVO);
                return CompanyVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询公司列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<CompanyVO>> pageCompanysForManager(CommonPage<CompanyQueryParams, Page<CompanyVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<CompanyQueryDTO, SysCompany> commonPageBuilder = new CommonPageBuilder<>(CompanyQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendParentCompanyCode("0")
                .appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<SysCompany> page = sysCompanyService.page(commonPageBuilder.bulid(), loginUser);
        List<SysCompany> Companys = page.getRecords();
        //结果对象
        IPage<CompanyVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(Companys)) {
            pageList.setRecords(Companys.stream().map(sysCompany -> {
                CompanyVO CompanyVO = new CompanyVO();
                BeanUtil.copyProperties(sysCompany, CompanyVO);
                return CompanyVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询公司列表信息--启用的公司
     *
     * @param queryParams
     * @return
     */
    public Result<List<CompanyVO>> queryCompanys(CompanyQueryParams queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CompanyQueryDTO queryDTO = new CompanyQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<SysCompany> companys = sysCompanyService.list(queryDTO, loginUser);
        //查询对象
        List<CompanyVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(companys)) {
            list = companys.stream().map(sysCompany -> {
                CompanyVO companyVO = new CompanyVO();
                BeanUtil.copyProperties(sysCompany, companyVO);
                return companyVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建公司
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createCompany(CompanyCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断CompanyKey是否存在
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyName(createParams.getCompanyName());
        new CompanyCheck(sysCompany).checkCompanyName(null, SysMsgCodeConstant.Error.ERR10000014);
        CompanyBuilder companyBuilder = new CompanyBuilder();
        companyBuilder.appendParentCompanyCode(loginUser.getCompanyCode()).append(createParams)
                .appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存公司信息
        if (!sysCompanyService.save(companyBuilder.bulid())) {
            log.info("保存公司接口异常,参数:{}", JSON.toJSONString(companyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //保存扩展信息
        CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();
        BeanUtil.copyProperties(createParams, companyInfoDTO);
        List<TemplateRecord> templateRecords = new TemplateFactory<CompanyInfoDTO>().readTemplate(companyInfoDTO);
        if (ObjectUtil.isNotEmpty(templateRecords)) {
            sysCompanyInfoService.saveBatch(templateRecords.stream().map(templateRecord -> {
                CompanyInfoBuilder companyInfoBuilder = new CompanyInfoBuilder();
                companyInfoBuilder.append(templateRecord).appendCode(companyBuilder.getCode()).appendCreate(loginUser);
                return companyInfoBuilder.bulid();
            }).collect(Collectors.toList()));
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, companyBuilder.getCode());
    }

    /**
     * 创建公司
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createCompanyForManager(CompanyCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断CompanyKey是否存在
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyName(createParams.getCompanyName());
        new CompanyCheck(sysCompany).checkCompanyName(null, SysMsgCodeConstant.Error.ERR10000014);
        CompanyBuilder companyBuilder = new CompanyBuilder();
        companyBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存公司信息
        if (!sysCompanyService.save(companyBuilder.bulid())) {
            log.info("保存公司接口异常,参数:{}", JSON.toJSONString(companyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //保存扩展信息
        CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();
        BeanUtil.copyProperties(createParams, companyInfoDTO);
        List<TemplateRecord> templateRecords = new TemplateFactory<CompanyInfoDTO>().readTemplate(companyInfoDTO);
        if (ObjectUtil.isNotEmpty(templateRecords)) {
            sysCompanyInfoService.saveBatch(templateRecords.stream().map(templateRecord -> {
                CompanyInfoBuilder companyInfoBuilder = new CompanyInfoBuilder();
                companyInfoBuilder.append(templateRecord).appendCode(companyBuilder.getCode()).appendCreate(loginUser);
                return companyInfoBuilder.bulid();
            }).collect(Collectors.toList()));
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, companyBuilder.getCode());
    }

    /**
     * 编辑公司
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editCompany(CompanyEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断CompanyKey是否存在
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyName(editParams.getCompanyName());
        new CompanyCheck(sysCompany).checkCompanyName(editParams.getCompanyCode(), SysMsgCodeConstant.Error.ERR10000014);
        CompanyBuilder companyBuilder = new CompanyBuilder();
        companyBuilder.append(editParams).appendEdit(loginUser);
        //编辑公司信息
        if (!sysCompanyService.edit(companyBuilder.bulid(), loginUser)) {
            log.info("编辑公司接口异常,参数:{}", JSON.toJSONString(companyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //删除信息
        sysCompanyInfoService.deleteCompanyInfo(editParams.getCompanyCode(), loginUser);
        //保存扩展信息
        CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();
        BeanUtil.copyProperties(editParams, companyInfoDTO);
        List<TemplateRecord> templateRecords = new TemplateFactory<CompanyInfoDTO>().readTemplate(companyInfoDTO);
        if (ObjectUtil.isNotEmpty(templateRecords)) {
            sysCompanyInfoService.saveBatch(templateRecords.stream().map(templateRecord -> {
                CompanyInfoBuilder companyInfoBuilder = new CompanyInfoBuilder();
                companyInfoBuilder.append(templateRecord).appendCode(editParams.getCompanyCode()).appendCreate(loginUser);
                return companyInfoBuilder.bulid();
            }).collect(Collectors.toList()));
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, companyBuilder.getCode());
    }


    /**
     * 删除公司
     *
     * @param companyCode 公司编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteCompany(String companyCode) {
        ValidateUtil.hasLength(companyCode, "参数[companyCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断是否有子公司
        Integer childConpanyCount = sysCompanyService.countChildCompany(companyCode);
        //获取权限信息
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyCode(companyCode, loginUser);
        new CompanyCheck(sysCompany).checkNull(SysMsgCodeConstant.Error.ERR10000002).checkNotHasChild(childConpanyCount, SysMsgCodeConstant.Error.ERR10000004);
        CompanyBuilder CompanyBuilder = new CompanyBuilder();
        CompanyBuilder.appendCode(companyCode).appendEdit(loginUser).delete();
        //删除公司信息
        if (!sysCompanyService.edit(CompanyBuilder.bulid(), loginUser)) {
            log.info("删除公司接口异常,参数:{}", JSON.toJSONString(CompanyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //删除公司相关 关联信息
        companyService.deleteLink(companyCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, CompanyBuilder.getCode());
    }

    /**
     * 开启公司
     *
     * @param companyCode 公司编码
     * @return Result
     */
    @Transactional
    public Result<String> openCompany(String companyCode) {
        ValidateUtil.hasLength(companyCode, "参数[companyCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyCode(companyCode, loginUser);
        new CompanyCheck(sysCompany).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        CompanyBuilder CompanyBuilder = new CompanyBuilder();
        CompanyBuilder.appendCode(companyCode).appendParentCompanyCode(sysCompany.getParentCompanyCode()).appendEdit(loginUser).open();
        //开启公司信息
        if (!sysCompanyService.edit(CompanyBuilder.bulid(), loginUser)) {
            log.info("开启公司接口异常,参数:{}", JSON.toJSONString(CompanyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, CompanyBuilder.getCode());
    }

    /**
     * 开启公司
     *
     * @param companyCode 公司编码
     * @return Result
     */
    @Transactional
    public Result<String> closeCompany(String companyCode) {
        ValidateUtil.hasLength(companyCode, "参数[companyCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyCode(companyCode, loginUser);
        new CompanyCheck(sysCompany).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        CompanyBuilder CompanyBuilder = new CompanyBuilder();
        CompanyBuilder.appendCode(companyCode).appendParentCompanyCode(sysCompany.getParentCompanyCode())
                .appendEdit(loginUser).close();
        //关闭公司信息
        if (!sysCompanyService.edit(CompanyBuilder.bulid(), loginUser)) {
            log.info("关闭公司接口异常,参数:{}", JSON.toJSONString(CompanyBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, CompanyBuilder.getCode());
    }

    /**
     * 公司详情
     *
     * @param companyCode 公司编码
     * @return Result
     */
    public Result<CompanyVO> viewCompany(String companyCode) {
        ValidateUtil.hasLength(companyCode, "参数[CompanyCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysCompany sysCompany = sysCompanyService.queryCompanyByCompanyCode(companyCode, loginUser);
        new CompanyCheck(sysCompany).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        CompanyVO companyVO = new CompanyVO();
        BeanUtil.copyProperties(sysCompany, companyVO);
        //查询上级公司信息
        SysCompany parentCompany = sysCompanyService.queryCompanyByCompanyCode(sysCompany.getParentCompanyCode(), loginUser);
        if (ObjectUtil.isNotNull(parentCompany)) {
            companyVO.setParentCompanyName(parentCompany.getCompanyName());
        }
        //设置附加信息
        List<TemplateRecord> templateRecords = sysCompanyInfoService.queryCompanyInfoByCompanyCode(companyCode, loginUser);
        CompanyInfoDTO companyInfoDTO = new TemplateFactory<CompanyInfoDTO>().readObject(templateRecords, CompanyInfoDTO.class);
        if (ObjectUtil.isNotNull(companyInfoDTO)) {
            BeanUtil.copyProperties(companyInfoDTO, companyVO);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, companyVO);
    }


    /**
     * 创建公司人员
     *
     * @param createParams
     * @return Result
     */
    @Transactional
    public Result<String> createAdmin(CompanyUserCreateParams createParams) {
        ValidateUtil.validate(createParams);
        LoginUser loginUser = LogInUserUtil.get();
        userService.createUser(createParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, createParams.getCompanyCode());
    }


    public Result<String> editAdmin(@Valid CompanyUserEditParams editParams) {
        ValidateUtil.validate(editParams);
        LoginUser loginUser = LogInUserUtil.get();
        if (StrUtil.isBlank(editParams.getCompanyCode())) {
            editParams.setCompanyCode(loginUser.getCompanyCode());
        }
        userService.editUser(editParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, editParams.getCompanyCode());
    }

    /**
     * 运营修改用户信心
     * @param editParams
     * @return
     */
    public Result<String> superEdit(@Valid AdminUserEditParams editParams) {
        ValidateUtil.validate(editParams);
        LoginUser loginUser = LogInUserUtil.get();
        userService.adminEditUser(editParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, editParams.getUserCode());
    }
}
